package com.spdg.ring.task;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import cn.wolf.base.BaseTask;
import cn.wolf.http.BaseResp;
import cn.wolf.http.HttpCallBack;
import cn.wolf.http.HttpRequest;
import cn.wolf.tools.Log;
import cn.wolf.tools.MD5;
import cn.wolf.tools.SdCardTool;
import cn.wolf.tools.StreamUtil;
import cn.wolf.tools.StringUtil;

import com.spdg.ring.R;
import com.spdg.ring.common.Config;
import com.spdg.ring.entity.MenuEntity;
import com.spdg.ring.resp.MenuResp;
import com.spdg.ring.sqlite.model.Menu;
import com.spdg.ring.xml.MenuParser;

/**
 * <p>Title:  获取菜单配置</p>
 * <p>Description:  </p>
 * <p>@author: caijj                </p>
 * <p>Copyright: Copyright (c) 2012    </p>
 * <p>Company: HX Co., Ltd.          </p>
 * <p>Create Time: 2012-10-20             </p>
 * <p>Update Time:                     </p>
 * <p>Updater:                         </p>
 * <p>Update Comments:                 </p>
 */
public class MenuTask extends BaseTask<Void, String, MenuResp> {

	private String url;
	private HttpURLConnection conn;

	public MenuTask(Context context, HttpCallBack<MenuResp> iCall, String url) {
		super(iCall, context);
		this.url = url;
	}

	@Override
	protected MenuResp doInBackground(Void... v) {

		HttpRequest request = new HttpRequest(MenuResp.class);
		MenuResp resp = new MenuResp();
		MenuEntity entity = new MenuEntity();
		List<Menu> menus = new ArrayList<Menu>();

		String progressTip = "";
		progressTip = mContext.getString(R.string.common_loading);
		publishProgress(progressTip); // 加载中，请稍候
		try {

			resp = (MenuResp) request.execute(url);

			String httpResult = resp.getHttpResult();
			if (!StringUtil.isEmpty(httpResult)) {
				ByteArrayInputStream input = new ByteArrayInputStream(httpResult.trim().getBytes());

				MenuParser parse = new MenuParser();
				entity = (MenuEntity) parse.parse(input);
				resp.setMenu(entity);

				menus = entity.getMenus();
				boolean mounted = SdCardTool.isMounted(); // sdcard是否挂载
				if (menus != null && mounted) {
					int size = menus.size();
					progressTip = mContext.getString(R.string.menu_loadprogress);
					for (int i = 0; i < size; i++) {
						Menu menu = menus.get(i);
						// 初始化栏目1/4
						progressTip = String.format(progressTip, (i + 1), size);

						publishProgress(progressTip); // 加载中，请稍候
						String cacheKey = MD5.getMD5Str(menu.getIcon());
						File file = createFile(Config.SDCARD_MENU_DIR, cacheKey);
						if (!file.exists() || file.length() <= 0) { // 本地不存在，下载图片
							download(menu.getIcon(), file);
						}
						
						String cacheKey2 = MD5.getMD5Str(menu.getIcon2());
						File file2 = createFile(Config.SDCARD_MENU_DIR, cacheKey2);
						if (!file2.exists() || file2.length() <= 0) { // 本地不存在，下载图片
							download(menu.getIcon2(), file2);
						}
					}
				}

				resp.setStatus(BaseResp.SUCCESS); // 解析成功

			}

		} catch (Exception e) {

		} finally {
			request.release();
		}

		return resp;
	}

	private File createFile(String cacheDir, String fileName) {

		File dir = new File(cacheDir);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File file = new File(cacheDir, fileName);
		return file;
	}

	private FileOutputStream createOutputStream(File file) {
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(file);
		} catch (FileNotFoundException e) {
			Log.e(e.getMessage() + ", file absolutePath:" + file.getAbsolutePath(), e);
			// e.printStackTrace();
			deleteFile(file);
		}

		return out;
	}

	@SuppressWarnings("unused")
	private void download(String url, File file) {

		FileOutputStream f = createOutputStream(file);
		try {
			InputStream in = download(url);
			if (in == null)
				return;
			int fix = 0;

			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				f.write(buffer, 0, len);
				fix += len;
			}
		} catch (MalformedURLException e) {
			// e.printStackTrace();
			Log.e(e.getMessage(), e);
			deleteFile(file);
		} catch (IOException e) {
			// e.printStackTrace();
			Log.e(e.getMessage(), e);
			deleteFile(file);
		} finally {
			// Closes this stream.
			StreamUtil.closeSilently(f);
			if (conn != null) {
				conn.disconnect();
			}
		}
	}

	private InputStream download(String url) {
		try {
			URL u = new URL(url);
			conn = ((HttpURLConnection) u.openConnection());
			conn.setRequestMethod("GET");
			conn.setDoOutput(true);
			conn.connect();

			return conn.getInputStream();
		} catch (MalformedURLException e) {
			// e.printStackTrace();
			Log.e(e.getMessage(), e);
		} catch (IOException e) {
			// e.printStackTrace();
			Log.e(e.getMessage(), e);
		}
		return null;
	}

	private void deleteFile(File file) {
		if (file != null && file.exists()) {
			file.delete();
		}
	}

}
